<script lang="ts">
  import { createEventDispatcher, onMount } from "svelte";
  import { selectOnFocus } from "../action";
  const dispatch = createEventDispatcher();

  export let autofocus: boolean = false;

  let name = "";
  let nameEl: HTMLElement;

  const addTodo = () => {
    dispatch("addTodo", name);
    name = "";
    nameEl.focus();
  };

  const onCancel = () => {
    name = "";
    nameEl.focus();
  };

  onMount(() => {
    if (autofocus) {
      nameEl.focus();
    }
  });
</script>

<form
  on:submit|preventDefault={addTodo}
  on:keydown={(e) => e.key === "Escape" && onCancel()}
>
  <h2 class="label-wrapper">
    <label for="todo-0" class="label__lg"> What needs to be done? </label>
  </h2>
  <input
    bind:value={name}
    bind:this={nameEl}
    use:selectOnFocus
    type="text"
    id="todo-0"
    autocomplete="off"
    class="input input__lg"
  />
  <button type="submit" class="btn btn__primary btn__lg" disabled={!name}
    >Add</button
  >
</form>
